<template>
  <div class="ssl-view">
    <div class="header">
      <div class="title-section">
        <h2>SSL 证书管理</h2>
        <el-tag type="success" class="ml-2">{{ totalCerts }} 个证书</el-tag>
      </div>
      <div class="actions">
        <!-- <el-button type="primary" :icon="Plus" @click="showAddCertDialog">添加证书</el-button> -->
      </div>
    </div>

    <div class="main-content">
      <el-table
        :data="certificates"
        style="width: 100%"
        border
      >
        <el-table-column prop="domain" label="域名">
          <template #default="{ row }">
            <div class="domain-cell">
              <span>{{ row.domain }}</span>
              <el-tag 
                size="small" 
                :type="row.status === 'valid' ? 'success' : 'danger'"
              >
                {{ row.status === 'valid' ? '有效' : '已过期' }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="issuer" label="颁发者" />
        
        <el-table-column label="有效期">
          <template #default="{ row }">
            <div class="validity-cell">
              <div class="dates">
                {{ row.not_before }} - {{ row.not_after }}
              </div>
              <el-progress
                :percentage="getValidityPercentage(row)"
                :status="getValidityStatus(row)"
                :stroke-width="5"
              />
            </div>
          </template>
        </el-table-column>
        
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button 
                type="primary" 
                link 
                :icon="View"
                @click="viewCertDetails(row)"
              >
                查看
              </el-button>
              <el-button 
                type="primary" 
                link 
                :icon="Download"
                @click="downloadCert(row)"
              >
                下载
              </el-button>
              <el-button 
                type="danger" 
                link 
                :icon="Delete"
                @click="deleteCert(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加证书对话框 -->
    <el-dialog
      v-model="addCertDialogVisible"
      title="添加 SSL 证书"
      width="600px"
    >
      <el-form
        ref="addCertFormRef"
        :model="addCertForm"
        :rules="addCertRules"
        label-width="100px"
      >
        <el-form-item label="域名" prop="domain">
          <el-input v-model="addCertForm.domain" placeholder="请输入域名" />
        </el-form-item>
        
        <el-form-item label="证书文件" prop="cert">
          <el-upload
            class="cert-upload"
            action="#"
            :auto-upload="false"
            :on-change="handleCertFileChange"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传 .pem 或 .crt 格式的证书文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="私钥文件" prop="key">
          <el-upload
            class="key-upload"
            action="#"
            :auto-upload="false"
            :on-change="handleKeyFileChange"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传 .key 格式的私钥文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addCertDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddCert">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 证书详情对话框 -->
    <el-dialog
      v-model="certDetailsDialogVisible"
      title="证书详情"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="域名">
          {{ selectedCert?.domain }}
        </el-descriptions-item>
        <el-descriptions-item label="颁发者">
          {{ selectedCert?.issuer }}
        </el-descriptions-item>
        <el-descriptions-item label="序列号">
          {{ selectedCert?.serialNumber }}
        </el-descriptions-item>
        <el-descriptions-item label="签名算法">
          {{ selectedCert?.signatureAlgorithm }}
        </el-descriptions-item>
        <el-descriptions-item label="有效期开始">
          {{ selectedCert?.not_before }}
        </el-descriptions-item>
        <el-descriptions-item label="有效期结束">
          {{ selectedCert?.not_after }}
        </el-descriptions-item>
        <el-descriptions-item label="指纹 (SHA-1)">
          {{ selectedCert?.fingerprint }}
        </el-descriptions-item>
        <el-descriptions-item label="证书路径">
          {{ selectedCert?.cert_path }}
        </el-descriptions-item>
        <el-descriptions-item label="私钥路径">
          {{ selectedCert?.key_path }}
        </el-descriptions-item>
        <el-descriptions-item label="SSL 协议">
          {{ selectedCert?.ssl_protocols }}
        </el-descriptions-item>
        <el-descriptions-item label="SSL 加密套件">
          {{ selectedCert?.ssl_ciphers }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { 
  Plus,
  View,
  Download,
  Delete
} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'
import { sslService, type SSLCertificate } from '@/services/ssl.service'

// 证书列表数据
const certificates = ref<SSLCertificate[]>([])

// 获取证书列表
const fetchCertificates = async () => {
  try {
    const certs = await sslService.getCertificates()
    certificates.value = certs
  } catch (error) {
    ElMessage.error('获取证书列表失败')
    console.error('获取证书列表失败:', error)
  }
}

// 在组件挂载时获取证书列表
onMounted(() => {
  fetchCertificates()
})

const totalCerts = computed(() => certificates.value.length)

// 计算证书有效期进度
const getValidityPercentage = (cert: SSLCertificate) => {
  const start = new Date(cert.not_before).getTime()
  const end = new Date(cert.not_after).getTime()
  const now = Date.now()
  
  return Math.round(((now - start) / (end - start)) * 100)
}

// 获取证书有效期状态
const getValidityStatus = (cert: SSLCertificate) => {
  const percentage = getValidityPercentage(cert)
  if (percentage >= 100) return 'exception'
  if (percentage >= 80) return 'warning'
  return 'success'
}

// 添加证书相关
const addCertDialogVisible = ref(false)
const addCertFormRef = ref<FormInstance>()
const addCertForm = ref({
  domain: '',
  cert: null as File | null,
  key: null as File | null
})

const addCertRules: FormRules = {
  domain: [
    { required: true, message: '请输入域名', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/, message: '请输入有效的域名', trigger: 'blur' }
  ],
  cert: [
    { required: true, message: '请上传证书文件', trigger: 'change' }
  ],
  key: [
    { required: true, message: '请上传私钥文件', trigger: 'change' }
  ]
}

const showAddCertDialog = () => {
  addCertDialogVisible.value = true
}

const handleCertFileChange = (file: File) => {
  addCertForm.value.cert = file
}

const handleKeyFileChange = (file: File) => {
  addCertForm.value.key = file
}

const submitAddCert = async () => {
  if (!addCertFormRef.value) return
  
  await addCertFormRef.value.validate(async (valid) => {
    if (valid && addCertForm.value.cert && addCertForm.value.key) {
      try {
        await sslService.addCertificate({
          domain: addCertForm.value.domain,
          cert: addCertForm.value.cert,
          key: addCertForm.value.key
        })
        ElMessage.success('证书添加成功')
        addCertDialogVisible.value = false
        // 重新获取证书列表
        await fetchCertificates()
      } catch (error) {
        ElMessage.error('证书添加失败')
        console.error('证书添加失败:', error)
      }
    }
  })
}

// 证书详情对话框
const certDetailsDialogVisible = ref(false)
const selectedCert = ref<SSLCertificate | null>(null)

const viewCertDetails = (cert: SSLCertificate) => {
  selectedCert.value = cert
  certDetailsDialogVisible.value = true
}

// 下载证书
const downloadCert = async (cert: SSLCertificate) => {
  try {
    const blob = await sslService.downloadCertificate(cert.domain)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${cert.domain}.zip`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success(`开始下载 ${cert.domain} 的证书`)
  } catch (error) {
    ElMessage.error('证书下载失败')
    console.error('证书下载失败:', error)
  }
}

// 删除证书
const deleteCert = (cert: SSLCertificate) => {
  ElMessageBox.confirm(
    `确定要删除 ${cert.domain} 的证书吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await sslService.deleteCertificate(cert.domain)
      ElMessage.success('证书删除成功')
      // 重新获取证书列表
      await fetchCertificates()
    } catch (error) {
      ElMessage.error('证书删除失败')
      console.error('证书删除失败:', error)
    }
  }).catch(() => {
    // 取消删除
  })
}
</script>

<style scoped>
.ssl-view {
  padding: 0 16px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section {
  display: flex;
  align-items: center;
}

.title-section h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.ml-2 {
  margin-left: 8px;
}

.domain-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.validity-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.dates {
  font-size: 13px;
  color: #606266;
}

.cert-upload,
.key-upload {
  :deep(.el-upload-list) {
    width: 360px;
  }
}

:deep(.el-progress-bar__inner) {
  transition: width 0.6s ease;
}
</style> 